package org.example.events.hostable.sales;

import org.example.models.abstracts.AbstractItem;
import org.example.models.interfaces.Action;
import org.example.models.interfaces.own.Ownable;
import org.example.person.Person;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//Set of actions for admin to manage sales
//TODO: change functions to return concrete class implementing action not lambda.
public class HostSalesActions {

    public static Action<Person> hostSales(SalesEvent salesEvent, List<? extends AbstractItem> items, Map<Class<? extends AbstractItem>, Integer> prices) {

        return (Person person) -> {
            if(salesEvent.isStarted()) return;

            List<Ownable> personOwnables = person.getOwnables();
            if (personOwnables.contains(salesEvent)) return;

            personOwnables.add(salesEvent);
            salesEvent.setStarted(true);
            Map<Class<? extends AbstractItem>, List<AbstractItem>> stock = new HashMap<>();
            for (var item : items) {
                if(!personOwnables.contains(item)) continue;
                stock.computeIfAbsent(item.getClass(), k -> new ArrayList<>()).add(item);
            }
            salesEvent.setStock(stock);
            salesEvent.setPrices(prices);
        };
    }

    public static Action<Person> stopSales(SalesEvent salesEvent) {
        return (Person person) -> {
            List<Ownable> personOwnables = person.getOwnables();
            if(!personOwnables.contains(salesEvent)) return;
            salesEvent.setStarted(false);
            personOwnables.remove(salesEvent);
        };
    }

    public static Action<Person> processClients(SalesEvent salesEvent) {
        return person -> {
            List<Ownable> personOwnables = person.getOwnables();
            if(!personOwnables.contains(salesEvent)) return;

            boolean success;
            do {
                success = salesEvent.processClient(new BuyAction(person));
            } while (success);
        };
    }
}
